#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
import random

import six

__all__ = ['load_fake_user_agent_db', 'get_user_agent']

user_agents = []
default_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko)' + \
                'Chrome/64.0.3282.186 Safari/537.36'


def load_fake_user_agent_db():
    global user_agents
    try:
        with open('static/fake_useragent_0.1.10.json', 'rb') as fp:
            db = json.load(fp)
            browsers = db['browsers']
            for browser, uas in six.iteritems(browsers):
                for ua in uas:
                    user_agents.append(ua)
    except IOError:
        user_agents = [default_agent]


def get_user_agent():
    global user_agents
    if len(user_agents) == 0:
        load_fake_user_agent_db()
    return random.choice(user_agents)
